using Engine;
using System.Globalization;
using Game.NetWork;
using Game.NetWork.Packages;
using Game;
using System;

namespace YS
{
    public class YSTo
    {
        private readonly ComponentPlayer _player;
        private readonly bool _isAdmin;

        // 通过构造函数注入玩家组件和权限状态
        public YSTo(ComponentPlayer player, bool isAdmin)
        {
            _player = player;
            _isAdmin = isAdmin;
        }

        public string ExecuteCommand(string[] messageData, bool wudiover)
        {
            // 冷却校验（普通玩家）
            if (!_isAdmin && !wudiover)
            {
                return "<c=red>传送间隔过短，请等待30秒后重试</c>";
            }

            // 参数校验
            if (messageData.Length != 5)
            {
                return "<c=red>格式错误！正确格式：/ys to X Y Z</c>\n示例：/ys to 120 64 -450";
            }

            // 坐标解析
            if (!TryParseCoordinates(messageData, out int x, out int y, out int z))
            {
                return "<c=red>坐标必须为整数！</c>\n示例：/ys to 100 64 -200";
            }

            // 普通玩家坐标限制
            if (!_isAdmin && (Math.Abs(x) > 500 || Math.Abs(z) > 500))
            {
                var pos = _player.ComponentBody.Position;
                return $"<c=yellow>只能在500m范围，你坐标超出安全区！当前位置：{pos.X:F0}, {pos.Y:F0}, {pos.Z:F0}</c>";
            }

            // 执行传送
            TeleportPlayer(x, y, z);
            return $"<c=green>传送完成 [{x}, {y}, {z}]</c> WuDiOver";
        }

        private bool TryParseCoordinates(string[] data, out int x, out int y, out int z)
        {
            x = y = z = 0;
            return int.TryParse(data[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out x)
                && int.TryParse(data[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out y)
                && int.TryParse(data[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out z);
        }

        private void TeleportPlayer(int x, int y, int z)
        {
            _player.ComponentBody.Position = new Vector3(x, y, z);
            CommonLib.Net.QueuePackage(new ComponentPlayerPackage(
                _player,
                ComponentPlayerPackage.PlayerAction.PositionSet
            ));
        }
    }
}